package sing.core.dialog;

import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;

import sing.core.R;

public class CustomDialog {

    private TextView tvTitle;//标题
    private LinearLayout ll; //内容
    private FrameLayout flParent; // 最外层
    private AppCompatButton confirm; //确定按钮
    private AppCompatButton cancel; //取消按钮
    public AlertDialog dialog;
    private View view;
    private Context context;

    public CustomDialog(Context context) {
        this.context = context;

        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        view = View.inflate(context, R.layout.dialog_base, null);
        tvTitle = view.findViewById(R.id.tv_title);
        ll = view.findViewById(R.id.parent);
        confirm = view.findViewById(R.id.confirm);
        cancel = view.findViewById(R.id.cancel);
        flParent = view.findViewById(R.id.flParent);

        builder.setView(view);
        dialog = builder.create();
    }

    public void setCancelable(boolean flag){
        dialog.setCanceledOnTouchOutside(flag);
        dialog.setCancelable(flag);
    }

    public void setTitle(String str) {
        tvTitle.setText(str);
    }

    public void setConfirm(String str) {
        confirm.setText(str);
    }

    public void setCancel(String str) {
        cancel.setText(str);
    }

    public void setView(View view) {
        ll.removeAllViews();
        ll.addView(view);
    }

    public void setMsg(String str) {
        TextView tv = new TextView(context);
        tv.setText(str);
        setView(tv);
    }

    public void hintCancel() {
        cancel.setVisibility(View.GONE);
    }

    public void hintConfirm() {
        confirm.setVisibility(View.GONE);
    }

    public void hintParent() {
        flParent.setVisibility(View.GONE);
    }

    public void addListener(OnClickListener listener) {
        if (listener != null) {
            if (confirm != null) {
                confirm.setOnClickListener(v -> listener.confirm(dialog));
            }
            if (cancel != null) {
                cancel.setOnClickListener(v -> listener.cancel(dialog));
            }
        }
    }

    public void show() {
        if (dialog != null) {
            dialog.show();
        }
    }

    public void dismiss() {
        if (dialog != null)
            dialog.dismiss();
    }

    public interface OnClickListener {
        default void cancel(AlertDialog dialog) {
            dialog.dismiss();
        }

        default void confirm(AlertDialog dialog) {
            dialog.dismiss();
        }
    }
}
